<?php
namespace jy_supplier_fee;
defined('BY_JYA') or exit('error');
/*
	招商员佣金计算
	
*/
class commission extends \plugin{
	function up_orderstatus($order_id=0,$merchid=0){
		$merchorder=pdo_get('jy_supplier_fee_order',array('uniacid'=>$_SESSION['uniacid'],'order_id'=>$order_id));
		if(!$merchorder['id']){
			$this->get_choufee($order_id,true,$merchid);
			return true;
		}
		$order=pdo_get('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order_id));
		if($order['status']==3){
			pdo_update('jy_supplier_fee_order',array('status'=>1),array('uniacid'=>$_SESSION['uniacid'],'order_id'=>$order_id));
		}
		return true;
	}
	/*
		根据订单生成佣金
	*/
	function get_zhaoshangorder($order){
		if(!$this->setting['isopen']){
			return false;
		}
		$dispatchprice=$order['dispatchprice'];
		$goodsorder=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order['id']));
		if(!count($goodsorder)){
			return false;
		}
		if($dispatchprice){
			$dispatchprice=$dispatchprice/count($goodsorder);
		}
		foreach($goodsorder as $item){
			if($item['api_pluginname']=='jy_supplier' && $item['api_id']){
				$merchid=$item['api_id'];
			}
			if(!$merchid){
				continue;
			}
			$zhaoshangid=pdo_getcolumn('jy_supplier_user',array('id'=>$merchid),'zhaoshangid');
			if($zhaoshangid){
				$this->create_commission($zhaoshangid,$item,$dispatchprice);
			}
		}
		return true;
	}
	/*
		给指定招商员计算分红
	*/
	function create_commission($zhaoshangid,$goodsorder,$dispatchprice=0){
			$zhaoshang=pdo_get('jy_supplier_fee_list',array('id'=>$zhaoshangid));
			$total_price=pdo_getcolumn('jy_weishop_order_goods',array('id'=>$goodsorder['id']),'total_price');
			$costprice=pdo_getcolumn('jy_weishop_goods',array('id'=>$goodsorder['goodsid']),'costprice');
			$total_costprice=$goodsorder['total']*$costprice;
			
			//获取默认等级佣金比例
			$zhaoshang['level_id']=$zhaoshang['level_id']?:0;
			if($zhaoshang['level_id']){
				$level=$this->get('level',array('id'=>$zhaoshang['level_id'],'uniacid'=>$_SESSION['uniacid']));
			}else{
				$level=$this->plugin_setting('default_level');
			}
			$commission_per=$level['fee_par'];
			if(substr($commission_per,-1)=='%'){
				$per=substr($commission_per,0,-1);
				if($this->setting['commissiontype']==1){
					$commission_money=($total_price*$per)/100;
				}elseif($this->setting['commissiontype']==3){
					$commission_money=(($total_price-$dispatchprice)*$per)/100;
				}else{					
					$commission_money=(($total_price-$total_costprice)*$per)/100;
				}
			}else{
				$commission_money=$commission_per;
			}
			$remark=array(
				'level_id'=>$zhaoshang['level_id'],
				'order_price'=>$total_price,
				'commission_money'=>$commission_money,
				'commission_per'=>$commission_per,
				'goods_commission'=>array(
					array('goods_id'=>$goodsorder['goodsid'],'total_price'=>$total_price,'total'=>$goodsorder['total'],'commission_per'=>$commission_per,'commission_money'=>$commission_money),
				),
			);
			$new_commission=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$zhaoshang['mid'],
				'zhaoshangid'=>$zhaoshangid,
				'area_code'=>$zhaoshang['code'],
				'level'=>$zhaoshang['level_id'],
				'orderid'=>$goodsorder['orderid'],
				'money'=>$commission_money,
				'remark'=>ijson_encode($remark),
				'commission_type'=>$commissioninfo['commissiontype']?:$this->setting['commissiontype'],
				'createtime'=>TIMESTAMP,
				'status'=>0,
			);
			$this->insert('commission',$new_commission);
			$agent_update=array(
				'order_price +='=>$total_price,
				'order_num +='=>1,
				'commission_money +='=>$commission_money,
			);
			$this->update('list',$agent_update,array('id'=>$agent['id']));
			$this->model('zhaoshang')->update_agent_level($zhaoshangid);
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order=array()){
		if($order['id']){
			$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('status'=>0,'orderid'=>$order['id']));
		}
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array()){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['pay_type']=='downline'){
			if(!$post['wechat']){
				exi('请先填写微信号！','error');
			}
			if(!$post['mobile']){
				exi('请先填写联系电话！','error');
			}
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低佣金检测
		if($money<1){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'wechat'=>$post['wechat'],
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn){
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金比例【{$goods['commission_per']}%】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='未启用';
		}
		$remark['level_title']=pdo_getcolumn('jy_supplier_fee_level',array('id'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
招商员等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}